package cn.jsu.oj.dispatchServer.satellite.handler;

import cn.jsu.oj.dispatchServer.satellite.annotation.HandlerType;
import cn.jsu.oj.dispatchServer.satellite.config.ResourceConfig;
import cn.jsu.oj.dispatchServer.satellite.factory.Factory;
import cn.jsu.oj.dispatchServer.satellite.mode.strategy.Strategy;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.LossNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.PackNet;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 失联处理器
 *
 * @author shan
 * @date 2022/07/07
 */
@Slf4j
@Component("lossHandler")
@HandlerType(typeNo = 9)
public class LossHandler implements Handler {

    @Autowired
    Factory handlerFactory;

    private static final String POSITION = ResourceConfig.getConfigString("client-active-position");

    private static final String PACK_ORIGIN = ResourceConfig.getConfigString("client-pack-origin");

    @Override
    public void handle(PackNet<?> packNet) {
        LossNet lossNet = (LossNet) packNet.getMessage();
        String missTarget = lossNet.getClient();
        if (!clientMemberCheck(missTarget)) {
            return;
        }
        Strategy strategy = (Strategy) Objects.requireNonNull
                (SpringUtil.getBean(POSITION + "Strategy")
                        , "----------策略获取失败......");
        strategy.setPremise(missTarget);
        strategy.execute();
    }

    private Boolean clientMemberCheck(String missTarget) {
        String[] clients = PACK_ORIGIN.split("\\|");
        for (String client : clients) {
            if (client.equals(missTarget)) {
                return true;
            }
        }
        return false;
    }
}
